package servlets;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import domainObjects.Dossier;
import beans.DossierInfractionBean;
import beans.InfractionBean;

/**
 * Servlet implementation class AjouterInfractionDossier
 */
public class AjouterInfractionDossier  extends javax.servlet.http.HttpServlet implements
javax.servlet.Servlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AjouterInfractionDossier() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		InfractionBean infractionBean = new InfractionBean(); 
		request.getSession().setAttribute("InfractionBean", infractionBean); // Scope: Session 
		response.sendRedirect ("/equipe6-log720-A11-lab2/AjouterInfractionDossier.jsp"); // redirection 
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		
		int id = -1;
		try {
			id = Integer.parseInt(request.getParameter("infractionID"));
		} catch (Exception e) {
			response.sendRedirect("/equipe6-log720-A11-lab2/AjouterInfractionDossier.jsp?Erreur=Infraction");
			return;
		}
		if(request.getSession().getAttribute("CurrentDossier") == null)
		{
			response.sendRedirect("/equipe6-log720-A11-lab2/AjouterInfractionDossier.jsp");
			return;
		}
		Dossier dossier = (Dossier)request.getSession().getAttribute("CurrentDossier");
		DossierInfractionBean dossierInfraction = new DossierInfractionBean();
		try {
			dossierInfraction.addInfraction(dossier.id(), id);
		} catch (SQLException e) {
			response.sendRedirect("/equipe6-log720-A11-lab2/AjouterInfractionDossier.jsp");
			return;
		}
		response.sendRedirect("/equipe6-log720-A11-lab2/AjouterInfractionDossier.jsp?Done=Ok"); // redirection
	}

}
